//
//  BindMailViewController.swift
//  ZhiTing
//
//  Created by zy on 2022/6/6.
//

import UIKit

class BindMailViewController: BaseViewController {
    
    @UserDefaultWrapper(key: .mailCaptchaId) var captcha_id: String?
    
    private lazy var mailTextField = TitleTextField(title: "邮箱".localizedString, placeHolder: "请输入邮箱地址".localizedString, isSecure: false).then {
        $0.limitCount = 100
    }
    
    private lazy var captchaButton = CaptchaButton(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
    
    private lazy var captchaTextField = TitleTextField(keyboardType: .numberPad, title: "获取验证码".localizedString, placeHolder: "请输入验证码".localizedString, limitCount: 6).then {
        $0.textField.rightViewMode = .always
        $0.textField.rightView = captchaButton
    }
    
    private lazy var captchaTips = Button().then {
        $0.setTitle("未收到验证码?".localizedString, for: .normal)
        $0.titleLabel?.font = .font(size: 14, type: .regular)
        $0.setTitleColor(.custom(.black_3f4663), for: .normal)
        $0.titleLabel?.textAlignment = .right
    }
    
    private lazy var doneButton = LoadingButton(title: "确定".localizedString)
        
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationItem.title = "绑定邮箱".localizedString

    }

    override func setupViews() {
        view.addSubview(mailTextField)
        view.addSubview(captchaTextField)
        view.addSubview(doneButton)
        view.addSubview(captchaTips)
        
        captchaButton.clickCallBack = { [weak self] _ in
            guard let self = self else { return }
            self.sendCaptcha()
        }
        
        captchaButton.endCountingCallback = { [weak self] in
            self?.mailTextField.isUserInteractionEnabled = true
        }
        
        doneButton.clickCallBack = { [weak self] _ in
            guard let self = self else { return }
            self.doneButtonClick()
        }
        
        captchaTips.addTarget(self, action: #selector(showCaptchaTips), for: .touchUpInside)
    }
    
    override func setupConstraints() {

        
        mailTextField.snp.makeConstraints {
            $0.top.equalTo(ZTScaleValue(75) + Screen.k_nav_height)
            $0.left.equalToSuperview().offset(ZTScaleValue(30))
            $0.right.equalToSuperview().offset(-ZTScaleValue(30))
        }
        
        captchaTextField.snp.makeConstraints {
            $0.top.equalTo(mailTextField.snp.bottom).offset(30 * Screen.screenRatio)
            $0.left.equalToSuperview().offset(ZTScaleValue(30))
            $0.right.equalToSuperview().offset(-ZTScaleValue(30))
        }
        
        doneButton.snp.makeConstraints {
            $0.bottom.equalTo(-160 * Screen.screenRatio)
            $0.centerX.equalToSuperview()
            $0.left.equalToSuperview().offset(ZTScaleValue(30))
            $0.right.equalToSuperview().offset(-ZTScaleValue(30))
            $0.height.equalTo(50)
        }
        
        captchaTips.snp.makeConstraints {
            $0.top.equalTo(doneButton.snp.bottom).offset(ZTScaleValue(25))
            $0.right.equalTo(doneButton)
            $0.width.greaterThanOrEqualTo(ZTScaleValue(100))
            $0.height.equalTo(ZTScaleValue(20))
        }
    }
    
    override func setupSubscriptions() {
        mailTextField.textPublisher
            .map { $0 != "" }
            .sink { [weak self] (isEnable) in
                guard let self = self else { return }
                self.captchaButton.setIsEnable(isEnable)
                
            }
            .store(in: &cancellables)
    
    }

}

extension BindMailViewController {
    
    @objc
    private func showCaptchaTips(){
        WarningAlert.show(message: "如果没有收到邮箱验证码，建议您进行以下操作：\n1、请您先确认输入的邮箱地址是否正确\n2、邮箱收不到验证码的话，请您先查看是否在\"垃圾箱\"中\n3、如果邮箱中找不到验证码，在\"垃圾箱\"中也找不到的话，可能是您的邮箱防火墙屏蔽了我们的邮箱，建议您使用一个兼容性更好的邮箱\n4、如果您尝试过以上的方法后依然无法收到验证码，请您联系我们的客服或在APP进行问题反馈，并提供您注册的账号名称、发生的具体时间", textAlignment: .left, title: "未收到验证码？", sureTitle: "知道了",iconImage: .assets(.icon_warning_light)) {

        }

    }
    
    private func sendCaptcha() {

        captchaButton.setIsEnable(false)
        captchaButton.btnLabel.text = "发送中...".localizedString
        //获取邮箱验证码
        ApiServiceManager.shared.sendEmailCaptcha(user_id: UserManager.shared.currentUser.user_id, email: mailTextField.text, type: .email_bind) {[weak self] response in
            guard let self = self else {return}
            self.showToast(string: "验证码已发送".localizedString)
            self.captchaButton.beginCountDown()
            self.mailTextField.isUserInteractionEnabled = false

            self.captcha_id = response.captcha_id
        } failureCallback: {[weak self] code, err in
            guard let self = self else {return}
            if err != "error" {
                self.showToast(string: err)
            }
            self.captchaButton.setIsEnable(true)
            self.captchaButton.btnLabel.text = "获取验证码".localizedString
        }
        
    }
    
    private func validateEmail(email: String) -> Bool{
        let mailPattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let emailTest: NSPredicate = NSPredicate(format: "SELF MATCHES %@", mailPattern)
        return emailTest.evaluate(with: email)
    }

    
    private func doneButtonClick() {
        

        if !(mailTextField.text.count > 0) {
            showToast(string: "邮箱地址不能为空".localizedString)
            return
        }
        
        if !validateEmail(email: mailTextField.text) {
            showToast(string: "请输入正确的邮箱地址")
            return
        }
        
        if !(captchaTextField.text.count > 0) {
            showToast(string: "验证码不能为空".localizedString)
            return
        }
        
        doneButton.buttonState = .waiting
        view.isUserInteractionEnabled = false
        
        //绑定
        ApiServiceManager.shared.editEmail(email: mailTextField.text, type: .email_bind, captcha: captchaTextField.text, captcha_id: captcha_id ?? "", verificationType: .email, new_email: nil, country_code: nil) {[weak self] response in
            guard let self = self else {return}
            self.showToast(string: "绑定成功")
            self.doneButton.buttonState = .normal
            self.view.isUserInteractionEnabled = false
 
            //更新用户信息
            ApiServiceManager.shared.cloudUserDetail(id: UserManager.shared.currentUser.user_id) { [weak self] (response) in
                guard let self = self else { return }
                /// 如果是云端的话 更新本地存储的用户信息
                UserManager.shared.currentUser = response.user_info
                UserCache.update(from: response.user_info)
                
                self.navigationController?.popViewController(animated: true)

            } failureCallback: { [weak self] (code, err) in
                guard let self = self else { return }
                self.showToast(string: err)
            }


        } failureCallback: {[weak self] code, err in
            guard let self = self else {return}
            self.showToast(string: err)
            self.doneButton.buttonState = .normal
            self.view.isUserInteractionEnabled = true

        }
        
    }
}
